﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Learning.ParticleAPI.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Title = "Home Page";

            return View();
        }

        public ActionResult SSEView()
        {
            return View();
        }

        public ActionResult Chat()
        {
            return View();
        }

        public void SSE()
        {
            Random random = new Random();

            //设置HTTP MIME 类型，不缓存页面
            Response.ContentType = "text/event-stream";
            Response.CacheControl = "no-cache";

            while (Response.IsClientConnected)
            {
                try
                {
                    string data = SSEData(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " from TEST");
                    Response.Write(data);
                    Response.Flush();

                    System.Threading.Thread.Sleep(random.Next(500, 5000));
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                }
            }

            Response.End();
            Response.Close();
        }

        private string SSEData(string data)
        {
            return $"data:{data}\n\n";
        }
    }
}
